import styles from './index.module.scss';
import Icon from '@/components/Icon';
import NavBar from '@/components/NavBar';
import { useParams } from 'react-router-dom';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';

import { useAppSelector } from '@/store';
import DOMPurify from 'dompurify';
import dayjs from 'dayjs';
import Skeleton from '@/components/Skeleton';
import hljs from 'highlight.js';
// 可以去项目下找到各种各样的主题风格
import 'highlight.js/styles/vs2015.css';
import classNames from 'classnames';
import NoComment from './components/NoComment';
import CommentItem from './components/CommentItem';
import CommentFooter from './components/CommentFooter';
import { Popup } from 'antd-mobile';
import CommentReply from './components/CommentReply';
import {
  getArticleByIdAction,
  clearArticleByIdAction,
} from '@/store/action/article';
import {
  clearCommentsAction,
  getArticleComByIdAction,
} from '@/store/action/comment';
import Share from './components/Share';

export default function Article() {
  const { id } = useParams<{ id: string }>();
  const dispatch = useDispatch();
  const { detail } = useAppSelector((state) => state.article);
  const wrapperRef = useRef<HTMLDivElement>(null);
  const [visible, setVisible] = useState(false);
  const authorRef = useRef<HTMLDivElement>(null);
  const { commentList, originComment } = useAppSelector(
    (state) => state.comments
  );

  useEffect(() => {
    dispatch(getArticleByIdAction(id));
    // 配置 highlight.js
    hljs.configure({
      // 忽略未经转义的 HTML 字符
      ignoreUnescapedHTML: true,
    });
    // 在article组件中判断art_id,如果不存在就显示骨架屏
    if (!detail.art_id) return;
    // 查找容器元素下符合 pre code 选择器规则的子元素，进行高亮
    const codes = document.querySelectorAll('.dg-html pre code');
    if (codes.length > 0) {
      return codes.forEach((el) => hljs.highlightElement(el as any));
    }

    // 查找容器元素下的 pre 元素，进行高亮
    const pre = document.querySelectorAll('.dg-html pre');
    if (pre.length > 0) {
      return pre.forEach((el) => hljs.highlightElement(el as any));
    }

    //对detail.art_id进行监听,数据一回来 就给pre和code标签加上样式效果
  }, [dispatch, id, detail.art_id]);

  useEffect(() => {
    return () => {
      dispatch(clearArticleByIdAction());
      dispatch(clearCommentsAction());
    };
  }, [dispatch]);

  // 监听事件滚动时触发
  useEffect(() => {
    if (!detail.art_id) return;
    const scrollFn = () => {
      const top = authorRef.current?.getBoundingClientRect().top as number;
      if (top > 10) {
        setVisible(false);
      } else {
        setVisible(true);
      }
    };
    const wrapperDom = wrapperRef.current;
    wrapperDom?.addEventListener('scroll', scrollFn);
    return () => {
      wrapperDom?.removeEventListener('scroll', scrollFn);
    };
  }, [detail.art_id]);

  // 将评论数据和loading'存入redux中
  useEffect(() => {
    if (!detail.art_id) return;
    dispatch(getArticleComByIdAction({ type: 'a', source: detail.art_id }));
  }, [detail.art_id, dispatch]);

  // 封装点击事件
  const commentRef = useRef<HTMLDivElement>(null);
  const handleScroll = () => {
    if (!wrapperRef.current) return;
    // 💥 offsetTop表示距离父级最高可滚动的高度
    // 💥 -50 表示不要被NavBar覆盖到
    wrapperRef.current.scrollTop = commentRef.current!.offsetTop - 50;
  };
  const [shareVisible, setShareVisible] = useState(false);
  const handleShowShare = () => setShareVisible(true);
  const handleCloseShare = () => setShareVisible(false);
  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        <NavBar right={<Icon type="icongengduo" />}>
          {visible && (
            <div className="nav-author">
              <img src={detail.aut_photo} alt="" />
              <span className="name">{detail.aut_name}</span>
              <span
                className={classNames(
                  'follow',
                  detail.is_followed ? 'followed' : ''
                )}
              >
                {detail.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          )}
        </NavBar>

        {/* 顶部导航栏 */}
        {/* <NavBar right={<Icon type="icongengduo" />}>文章标题</NavBar> */}

        {!!detail.art_id ? (
          <div className="wrapper" ref={wrapperRef}>
            <div className="article-wrapper">
              {/* 文章描述信息栏 */}
              <div className="header">
                <h1 className="title">{detail.title}</h1>

                <div className="info">
                  <span>{'2020-10-10'}</span>
                  <span>{detail.read_count} 阅读</span>
                  <span>{detail.comm_count} 评论</span>
                </div>

                <div className="author" ref={authorRef}>
                  <img src={detail.aut_photo} alt="" />
                  <span className="name">{detail.aut_name}</span>
                  <span className="follow">关注</span>
                </div>
              </div>

              {/* 文章正文内容区域 */}
              <div className="content">
                <div
                  className="content-html dg-html"
                  dangerouslySetInnerHTML={{
                    __html: DOMPurify.sanitize(detail.content),
                  }}
                ></div>
                <div className="date">
                  发布文章时间：{dayjs().from(detail.pubdate)}
                </div>
                {/* 💥 注意和date同级 */}
                <div className="divider"></div>
                <div className="comment" ref={commentRef}>
                  {/* 评论总览信息 */}
                  <div className="comment-header">
                    <span>全部评论（{detail.comm_count}）</span>
                    <span>{detail.like_count} 点赞</span>
                  </div>
                  {/* 评论列表 */}
                  {detail.comm_count === 0 ? (
                    <NoComment />
                  ) : (
                    commentList.map((item) => {
                      return (
                        <div className="comment-list">
                          <CommentItem comment={item} key={item.aut_id} />
                        </div>
                      );
                    })
                  )}
                </div>
              </div>
            </div>
          </div>
        ) : (
          <Skeleton></Skeleton>
        )}
      </div>
      <CommentFooter
        onShare={handleShowShare}
        onClick={handleScroll}
        articleData={detail}
      ></CommentFooter>
      {/* 0.设置一个右侧弹出层 ，通过原始的评论数据驱动的*/}
      {/* 6.com_id判断是否存在，显示或不显示右侧弹出层 */}
      {/* 关闭时记得销毁 */}
      <Popup destroyOnClose visible={!!originComment.com_id} position="right">
        <CommentReply></CommentReply>
      </Popup>
      <Popup visible={shareVisible}>
        <Share onClose={handleCloseShare}></Share>
      </Popup>
    </div>
  );
}
